import { deepClone } from '@/utils/share';
import { ref, watch } from 'vue';

/** hooks 参数 */
type UsePagingParams = {
  getPaging: (params: Record<string, any>) => Promise<any>;
  extraParams: { extraParams: Record<string, any> };
};

const usePaging = ({ getPaging, extraParams }: UsePagingParams) => {
  // 分页数组
  const list = ref<any[]>([]);
  // 分页参数
  const pagingParams = ref<Record<'current' | 'size', number>>({ current: 0, size: 10 });
  // 滚动加载
  const loading = ref<boolean>(false);
  // 是否没有数据加载了
  const finished = ref<boolean>(false);
  // 下拉刷新loading
  const refreshing = ref<boolean>(false);
  // 是否出错
  const error = ref<boolean>(false);
  // 缓存分页参数
  const cachePrams = ref<any>(null);
  // 首次加载完数据
  const firstLoaded = ref<any>(false);

  // 请求列表数据
  const fetchList = async () => {
    // 深拷贝数据
    const temp = deepClone(list.value);

    if (!refreshing.value) {
      pagingParams.value = {
        current: pagingParams.value.current + 1,
        size: 10,
      };
    }

    try {
      const {
        content: { records = [], total },
      } = await getPaging({ ...pagingParams.value, ...extraParams.extraParams });
      if (refreshing.value) {
        list.value = records;
      } else {
        list.value = temp.concat(records);
      }
      if (list.value.length >= total || !total || !records.length) {
        finished.value = true;
      } else {
        finished.value = false;
      }
      firstLoaded.value = true;
      console.log(firstLoaded.value);
    } catch {
      error.value = true;
    } finally {
      refreshing.value = false;
      loading.value = false;
    }
  };

  // 加载数据
  const onLoad = () => {
    cachePrams.value = deepClone(extraParams.extraParams);
    loading.value = true;
    fetchList();
  };

  /** 刷新页面 */
  const reload = async () => {
    pagingParams.value = {
      current: 1,
      size: 10,
    };
    refreshing.value = true;
    error.value = false;
    await fetchList();
  };

  const onRefresh = () => {
    reload();
  };

  watch(
    () => extraParams.extraParams,
    () => {
      // 如果是初始化则不执行watch请求
      if (!cachePrams.value) {
        return;
      }

      if (JSON.stringify(cachePrams.value) !== JSON.stringify(extraParams.extraParams)) {
        cachePrams.value = extraParams.extraParams;
        reload();
      }
    }
  );

  return { list, finished, firstLoaded, loading, refreshing, error, onLoad, onRefresh, reload };
};

export default usePaging;
